package me.like.diandian.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import androidx.core.content.FileProvider;
import androidx.viewpager.widget.ViewPager;

import com.tencent.mm.opensdk.openapi.IWXAPI;

import org.json.JSONException;

import java.io.File;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.like.diandian.BaseApplication1;
import me.like.diandian.bean.LoanMarketListBean;

/**
 * Created by Administrator on 2016/11/22.
 */

public class CommonUtils {


    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static String loanSubTitle(LoanMarketListBean bean) {
        String s = String.format("可贷额度:%s-%s元，利率:日息%s", bean.getMinBorrow(), bean.getMaxBorrow(), bean.getMinDayRate()) + "%";
        return s;
    }

    /**
     * @param @param  context
     * @param @return
     * @return String
     * @throws
     * @Title: getVersionName
     * @Description: 获取当前应用的版本号
     */
    public static String getVersionName() {
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = BaseApplication1.getInstance().getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo;
            packInfo = packageManager.getPackageInfo(BaseApplication1.getInstance().getPackageName(),
                    0);
            String version = packInfo.versionName;
            return version;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }


    public static int getVersionCode() {
        PackageInfo packInfo = null;
        try {
            PackageManager packageManager = BaseApplication1.getInstance().getPackageManager();
            packInfo = packageManager.getPackageInfo(BaseApplication1.getInstance().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packInfo != null ? packInfo.versionCode : 0;
    }

    // 安装下载后的apk文件
    public static void instanll(File file, Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);

        Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);

        intent.setDataAndType(photoURI,
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static int getScreenMaxWidth(Context context, int paramInt) {
        Object localObject = new DisplayMetrics();
        try {
            DisplayMetrics localDisplayMetrics =
                    context.getApplicationContext().getResources().getDisplayMetrics();
            localObject = localDisplayMetrics;
            return ((DisplayMetrics) localObject).widthPixels - dip2px(context, paramInt);
        } catch (Exception localException) {
            while (true) {
                localException.printStackTrace();
                ((DisplayMetrics) localObject).widthPixels = 640;
            }
        }
    }


    /**
     * 获取屏幕分辨率宽
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        // ((Activity)
        // context).getWindowManager().getDefaultDisplay().getMetrics(dm);

        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        display.getMetrics(dm);

        return dm.widthPixels;
    }

    /**
     * 讲电话号码中间变成*
     *
     * @param pNumber
     * @return
     */
    public static String changeTel(String pNumber) {
        if (!TextUtils.isEmpty(pNumber) && pNumber.length() > 6) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < pNumber.length(); i++) {
                char c = pNumber.charAt(i);
                if (i >= 3 && i <= 6) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }
            return sb.toString();
        }
        return pNumber;
    }

    public static boolean matchPhone(String text) {
//        if (Pattern.compile("^1(3|4|5|7|8)\\d{9}$").matcher(text).matches()) {
//            return true;
//        }
//        return false;
        if (text == null) {
            return false;
        }
        Pattern p = Pattern.compile("^[1-9]\\d{10}$");
        Matcher m = p.matcher(text);
        return m.matches();
    }


    /**
     * HTTP请求签名
     *
     * @return
     */
    public static String generateSign() {
//        StringBuilder builder = new StringBuilder(BaseConstant.secretKey);
        StringBuilder builder = new StringBuilder("timestamp=" + System.currentTimeMillis());
        builder.append(SPUtils.getToken(BaseApplication1.getInstance()));
        String s = builder.toString();
//        MD5Utils.MD5Encode("s","utf8");
        Log.i("infoss", s);
        s = md5(s);
        Log.i("infoss", s);
        return s;
    }

    private static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getBorrow(int minBorrow, int maxBorrow) {

        return getMoney(minBorrow) + "~" + getMoney(maxBorrow);
    }

    public static String getMoney(int money) {
//        if (String.valueOf(money).endsWith("0000")) {
//            return (money / 10000) + "万";
//        } else if (String.valueOf(money).endsWith("000")) {
//            return (money / 1000) + "千";
//        }
        return String.valueOf(money);
    }

    public static String getLimit(int minLimit, int maxLimit) {
        return "贷款期限" + minLimit + "~" + maxLimit + "日";
    }

    public static String getfastLoanTime(String fastestLoanTime) {
        if (TextUtils.isEmpty(fastestLoanTime)) {
            fastestLoanTime = "0";
        }
        return "最快" + fastestLoanTime + "分钟放款";
    }

    /**
     * 获取bitmap图片的大小
     *
     * @param bitmap
     * @return
     */
    public static long getBitmapsize(Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            return bitmap.getByteCount();
        }
        // Pre HC-MR1
        return bitmap.getRowBytes() * bitmap.getHeight();

    }

    /**
     * 获取bitmap图片的大小后转换成kb
     *
     * @param bitmap
     * @return
     */
    public static String convertFileSize(Bitmap bitmap) {
        long kb = 1024;
        float f = (float) getBitmapsize(bitmap) / kb;
        return String.format(f > 100 ? "%.0f" : "%.1f", f);
    }


    /**
     * 安卓获取状态栏(Status Bar)高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        Log.v("dbw", "Status height:" + height);
        return height;
    }

    public static int dp2px(Context context, float dpValue) {
        int densityDpi = context.getResources().getDisplayMetrics().densityDpi;
        return (int) (dpValue * (densityDpi / 160));
    }

    /**
     * 判断是否有虚拟按键
     *
     * @param context
     * @return
     */
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }

    public static void hideBottomUIMenu(Activity context) {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = context.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = context.getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }


    /**
     * 获取 虚拟按键的高度
     *
     * @param context
     * @return
     */
    public static int getBottomStatusHeight(Context context) {
        int totalHeight = getDpi(context);

        int contentHeight = getScreenHeight(context);

        return totalHeight - contentHeight;
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    //获取屏幕原始尺寸高度，包括虚拟功能键高度
    public static int getDpi(Context context) {
        int dpi = 0;
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, displayMetrics);
            dpi = displayMetrics.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dpi;
    }


    public static void setWidthAndHeight(Context context, ViewPager pager, int width, int height) {
        int screenWidth = getScreenWidth(context);
        int sheight = screenWidth * height / width;
        ViewGroup.LayoutParams layoutParams = pager.getLayoutParams();
        layoutParams.height = sheight;
        pager.setLayoutParams(layoutParams);
    }


    /**
     * 分享
     *
     * @param context
     * @throws JSONException
     */
    public static void share(Context context, String text) throws JSONException {

//        SharePopup sharePopup = new SharePopup();
//        PopupWindow popup = sharePopup.harePopup((Activity) context);
//        sharePopup.setShareItemListener(new SharePopup.onShareItemListener() {
//            @Override
//            public void onItemClick(int position) {
//
//            }
//        });
//        sharePopup.setShareItemListener((int position) -> {
//            int wxSceneSession = -1;
//            switch (position) {
//                case 0:
//                    if (isWeChatAppInstalled(context, BaseApplication1.api)) {
//                        //初始化一个 WXTextObject 对象，填写分享的文本内容
//                        wxSceneSession = SendMessageToWX.Req.WXSceneSession;
//                    } else {
//                        ToastView.initToast().textToast(context, "您尚未安装微信");
//                    }
//                    break;
//                case 1:
//                    if (isWeChatAppInstalled(context, BaseApplication1.api)) {
//                        wxSceneSession = SendMessageToWX.Req.WXSceneTimeline;
//                    } else {
//                        ToastView.initToast().textToast(context, "您尚未安装微信");
//                    }
//
//                    break;
//
//                default:
//                    break;
//            }
//            if (wxSceneSession >= 0) {
//
//                WXTextObject textObj = new WXTextObject();
//                textObj.text = text;
//
////用 WXTextObject 对象初始化一个 WXMediaMessage 对象
//                WXMediaMessage msg = new WXMediaMessage();
//                msg.mediaObject = textObj;
//                msg.description = text;
//
//                SendMessageToWX.Req req = new SendMessageToWX.Req();
////                req.transaction = buildTransaction("text");
//                req.message = msg;
//                req.scene = wxSceneSession;
//                IWXAPI api = WXAPIFactory.createWXAPI(context, WX_APP_ID, true);
//                api.registerApp(WX_APP_ID);
//                api.sendReq(req);
//            }
//        });
//        popup.showAtLocation(((ViewGroup) ((Activity) context).findViewById(android.R.id.content))
//                        .getChildAt(0),
//                Gravity.CENTER, 0, 0);
    }


    /**
     * 两个String数组拼接
     *
     * @param a
     * @param b
     * @return
     */
    public static String[] concat(String[] a, String[] b) {
        String[] c = new String[a.length + b.length];
        System.arraycopy(a, 0, c, 0, a.length);
        System.arraycopy(b, 0, c, a.length, b.length);
        return c;
    }


    /**
     * 通过包名判断有没有安装某个应用
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isAppInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        List<String> pName = new ArrayList<String>();
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);
    }


    public static boolean isWeChatAppInstalled(Context context, IWXAPI api) {
        if (api.isWXAppInstalled()) {
            return true;
        } else {
            final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if ("com.tencent.mm".equalsIgnoreCase(pn)) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if ("com.tencent.mobileqq".equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 检测当的网络（WLAN、3G/2G）状态
     *
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }


}
